//
//  MoreViewController.m
//  WXMovie
//
//  Created by apple on 16/3/29.
//  Copyright © 2016年 zic_magic. All rights reserved.
//

#import "MoreViewController.h"

@interface MoreViewController () <UIImagePickerControllerDelegate, UINavigationControllerDelegate>
{
    NSString *userName;
    UIImage *userIcon;
}
@end

@implementation MoreViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_main@2x"]];
    self.title = @"更多";
    [self getDataFromSandBox];
//    self.tableView.separatorInset = UIEdgeInsetsMake(50, 0, 0, 0);
//    NSLog(@"%@", NSHomeDirectory());
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, 150)];
    headView.backgroundColor = [UIColor clearColor];
    self.tableView.tableHeaderView = headView;
    
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.frame = CGRectMake(25, 25, 100, 100);
    button.layer.cornerRadius = 50;
    button.layer.masksToBounds = YES;
    [button setImage:userIcon forState:UIControlStateNormal];
    [button setTitle:@"编辑" forState:UIControlStateHighlighted];
    [button addTarget:self action:@selector(buttonAction:) forControlEvents:UIControlEventTouchUpInside];
    button.tag = 1000;
    [headView addSubview:button];
    
    UILabel *nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(150, 25, 200, 40)];
    nameLabel.textAlignment = NSTextAlignmentLeft;
    nameLabel.textColor = [UIColor cyanColor];
    nameLabel.text = userName;
    nameLabel.tag = 2000;
    [headView addSubview:nameLabel];
    [self.tableView reloadData];
    
}

- (void)buttonAction:(UIButton *)button {
    
    UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
    imagePicker.sourceType = UIImagePickerControllerSourceTypeSavedPhotosAlbum;
    imagePicker.delegate = self;
    
    [self presentViewController:imagePicker animated:YES completion:NULL];
    
}
//获取图片的delegate 在相册中选择图片时调用
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    userIcon = image;
    UIButton *button = [self.tableView.tableHeaderView viewWithTag:1000];
    [button setImage:image forState:UIControlStateNormal];
    
    UILabel *label = [self.tableView.tableHeaderView viewWithTag:2000];
    userName = @"BigBang";
    label.text = userName;
    
    [self saveDataToSandBox];
    
}
//保存数据到沙盒中
- (void)saveDataToSandBox {
    
    if (userIcon != nil) {
        
        [[NSUserDefaults standardUserDefaults] setObject:userName forKey:@"userName"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
        NSData *data = UIImageJPEGRepresentation(userIcon, 0.8);
        [[NSUserDefaults standardUserDefaults] setObject:data forKey:@"userIcon"];
        [[NSUserDefaults standardUserDefaults] synchronize];
        
    }
}
//从沙盒中获取文件
- (void)getDataFromSandBox {
    
    userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"userName"];
    userIcon = [UIImage imageWithData:[[NSUserDefaults standardUserDefaults] objectForKey:@"userIcon"]];
    
    [[NSUserDefaults standardUserDefaults] synchronize];
    
}


- (void)viewWillAppear:(BOOL)animated {
    
    [super viewWillAppear:YES];
    
    [self readCatchSize];
}

- (void)readCatchSize {
    
//    NSInteger fileSize = [[SDImageCache sharedImageCache] getSize];
    
    NSInteger fileSize = [self getCatchSize];
    self.sizeLabel.text = [NSString stringWithFormat:@"%.2f MB", fileSize / 1024.0 / 1024.0];
    
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    if (indexPath.row == 0 && indexPath.section == 0) {

        
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提示" message:[NSString stringWithFormat:@"确定清除缓存%@", self.sizeLabel.text] preferredStyle:UIAlertControllerStyleAlert];
        [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            
//            [[SDImageCache sharedImageCache] clearDisk];
//            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationNone];
            [self clearCatch];
            [self readCatchSize];
            
        
            
        }]];
        [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:NULL]];
        [self presentViewController:alert animated:YES completion:NULL];

    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (NSInteger)getCatchSize {
    
    NSInteger fileSize = 0;
    
    NSString *catchPath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    NSDirectoryEnumerator *fileEnumerator = [[NSFileManager defaultManager] enumeratorAtPath:catchPath];
    
    for (NSString *fileName in fileEnumerator) {
       
        NSString *filePath = [catchPath stringByAppendingPathComponent:fileName];
        NSDictionary *attDic = [[NSFileManager defaultManager] attributesOfItemAtPath:filePath error:nil];
        fileSize += [attDic fileSize];
        
    }
    return fileSize;
}

- (void)clearCatch {
    

     NSString *filePath = [NSHomeDirectory() stringByAppendingPathComponent:@"Library/Caches"];
    [[NSFileManager defaultManager] removeItemAtPath:filePath error:NULL];
    

}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
